import React, { useState, useEffect, useCallback } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  Modal,
  FlatList,
  StyleSheet,
  Alert,
} from 'react-native'
import { Icon } from '@rneui/themed'
import pcaData from '../assets/pca-code.json'

export interface Region {
  code: string
  name: string
  children?: Region[]
}

interface RegionSelectorProps {
  visible: boolean
  onClose: () => void
  onConfirm: (selectedRegions: Region[]) => void
  title?: string
}

export const RegionSelector: React.FC<RegionSelectorProps> = ({
  visible,
  onClose,
  onConfirm,
  title = '选择地区',
}) => {
  const [provinces, setProvinces] = useState<Region[]>([])
  const [cities, setCities] = useState<Region[]>([])
  const [districts, setDistricts] = useState<Region[]>([])
  const [selectedProvince, setSelectedProvince] = useState<Region | null>(null)
  const [selectedCity, setSelectedCity] = useState<Region | null>(null)
  const [selectedDistrict, setSelectedDistrict] = useState<Region | null>(null)
  const [currentLevel, setCurrentLevel] = useState<'province' | 'city' | 'district'>('province')

  const loadRegionData = useCallback(() => {
    setProvinces(pcaData)
    setCurrentLevel('province')
    setCities([])
    setDistricts([])
    setSelectedProvince(null)
    setSelectedCity(null)
    setSelectedDistrict(null)
  }, [])

  // 当选择器显示时加载数据
  useEffect(() => {
    if (visible) {
      loadRegionData()
    }
  }, [visible, loadRegionData])

  const handleProvinceSelect = (province: Region) => {
    setSelectedProvince(province)
    setCities(province.children || [])
    setDistricts([])
    setCurrentLevel('city')
  }

  const handleCitySelect = (city: Region) => {
    setSelectedCity(city)
    setDistricts(city.children || [])
    setCurrentLevel('district')
  }

  const handleDistrictSelect = (district: Region) => {
    setSelectedDistrict(district)
    // 选择完成后自动确认
    const selectedRegions = [selectedProvince!, selectedCity!, district]
    onConfirm(selectedRegions)
    onClose()
  }

  const handleConfirm = () => {
    if (selectedProvince && selectedCity && selectedDistrict) {
      const selectedRegions = [selectedProvince, selectedCity, selectedDistrict]
      onConfirm(selectedRegions)
      onClose()
    } else {
      Alert.alert('提示', '请选择完整的省市区')
    }
  }

  const renderRegionItem = ({ item }: { item: Region }) => {
    const isSelected = 
      (currentLevel === 'province' && selectedProvince?.code === item.code) ||
      (currentLevel === 'city' && selectedCity?.code === item.code) ||
      (currentLevel === 'district' && selectedDistrict?.code === item.code)

    return (
      <TouchableOpacity
        style={[styles.regionItem, isSelected && styles.selectedRegionItem]}
        onPress={() => {
          if (currentLevel === 'province') {
            handleProvinceSelect(item)
          } else if (currentLevel === 'city') {
            handleCitySelect(item)
          } else if (currentLevel === 'district') {
            handleDistrictSelect(item)
          }
        }}
      >
        <Text style={[styles.regionName, isSelected && styles.selectedRegionName]}>
          {item.name}
        </Text>
        {item.children && item.children.length > 0 && (
          <Icon name="chevron-right" type="feather" size={16} color="#666" />
        )}
      </TouchableOpacity>
    )
  }

  const getCurrentTitle = () => {
    switch (currentLevel) {
      case 'province':
        return '选择省份'
      case 'city':
        return `选择城市 - ${selectedProvince?.name}`
      case 'district':
        return `选择区县 - ${selectedCity?.name}`
      default:
        return title
    }
  }

  const getCurrentData = () => {
    switch (currentLevel) {
      case 'province':
        return provinces
      case 'city':
        return cities
      case 'district':
        return districts
      default:
        return []
    }
  }

  const getSelectedPath = () => {
    let path = ''
    if (selectedProvince) path += selectedProvince.name
    if (selectedCity) path += ` / ${selectedCity.name}`
    if (selectedDistrict) path += ` / ${selectedDistrict.name}`
    return path || '请选择地区'
  }

  return (
    <Modal
      visible={visible}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={onClose}
    >
      <View style={styles.container}>
        {/* Header */}
        <View style={styles.header}>
          <TouchableOpacity onPress={onClose}>
            <Text style={styles.cancelButton}>取消</Text>
          </TouchableOpacity>
          <Text style={styles.title}>{getCurrentTitle()}</Text>
          <TouchableOpacity onPress={handleConfirm}>
            <Text style={styles.confirmButton}>确定</Text>
          </TouchableOpacity>
        </View>

        {/* 选择路径显示 */}
        <View style={styles.pathContainer}>
          <Text style={styles.pathText}>{getSelectedPath()}</Text>
        </View>

        {/* 面包屑导航 */}
        <View style={styles.breadcrumb}>
          <TouchableOpacity
            style={[styles.breadcrumbItem, currentLevel === 'province' && styles.activeBreadcrumb]}
            onPress={() => {
              setCurrentLevel('province')
              setCities([])
              setDistricts([])
              setSelectedCity(null)
              setSelectedDistrict(null)
            }}
          >
            <Text style={[styles.breadcrumbText, currentLevel === 'province' && styles.activeBreadcrumbText]}>
              省份
            </Text>
          </TouchableOpacity>
          
          {selectedProvince && (
            <TouchableOpacity
              style={[styles.breadcrumbItem, currentLevel === 'city' && styles.activeBreadcrumb]}
              onPress={() => {
                setCurrentLevel('city')
                setDistricts([])
                setSelectedDistrict(null)
              }}
            >
              <Text style={[styles.breadcrumbText, currentLevel === 'city' && styles.activeBreadcrumbText]}>
                {selectedProvince.name}
              </Text>
            </TouchableOpacity>
          )}
          
          {selectedCity && (
            <TouchableOpacity
              style={[styles.breadcrumbItem, currentLevel === 'district' && styles.activeBreadcrumb]}
              onPress={() => setCurrentLevel('district')}
            >
              <Text style={[styles.breadcrumbText, currentLevel === 'district' && styles.activeBreadcrumbText]}>
                {selectedCity.name}
              </Text>
            </TouchableOpacity>
          )}
        </View>

        {/* 地区列表 */}
        <FlatList
          data={getCurrentData()}
          keyExtractor={(item) => item.code}
          renderItem={renderRegionItem}
          style={styles.regionList}
          showsVerticalScrollIndicator={false}
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <Text style={styles.emptyText}>暂无数据</Text>
            </View>
          }
        />
      </View>
    </Modal>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5e5',
  },
  cancelButton: {
    fontSize: 16,
    color: '#666',
  },
  title: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  confirmButton: {
    fontSize: 16,
    color: '#409EFF',
    fontWeight: '600',
  },
  pathContainer: {
    backgroundColor: '#fff',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5e5',
  },
  pathText: {
    fontSize: 16,
    color: '#333',
    fontWeight: '500',
  },
  breadcrumb: {
    flexDirection: 'row',
    backgroundColor: '#fff',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5e5',
  },
  breadcrumbItem: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    marginRight: 8,
    borderRadius: 16,
    backgroundColor: '#f0f0f0',
  },
  activeBreadcrumb: {
    backgroundColor: '#409EFF',
  },
  breadcrumbText: {
    fontSize: 14,
    color: '#666',
  },
  activeBreadcrumbText: {
    color: '#fff',
    fontWeight: '500',
  },
  regionList: {
    flex: 1,
    backgroundColor: '#fff',
  },
  regionItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  selectedRegionItem: {
    backgroundColor: '#f0f7ff',
  },
  regionName: {
    fontSize: 16,
    color: '#333',
    flex: 1,
  },
  selectedRegionName: {
    color: '#409EFF',
    fontWeight: '500',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 50,
  },
  emptyText: {
    fontSize: 16,
    color: '#999',
  },
})
